package com.lsh.ofc.core.handler;

import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.model.CommonResult;
import com.lsh.ofc.core.entity.OfcSoHead;
import com.lsh.ofc.core.entity.OfcSupplier;
import com.lsh.ofc.core.enums.OfcTaskType;
import com.lsh.ofc.core.service.OfcTaskService;
import com.lsh.ofc.core.service.SupplierConfigService;
import com.lsh.ofc.core.service.impl.AbstractCancelOrderService;
import com.lsh.ofc.proxy.service.OpenApiServiceProxy;
import com.lsh.ofc.proxy.service.WgServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author miaozhuang
 * @date 18/3/28
 */
@Service("cancelOrderByWgHandler")
@Slf4j
public class CancelOrderByWgHandler extends AbstractCancelOrderService {

    @Autowired
    private WgServiceProxy wgServiceProxy;

    @Resource
    private SupplierConfigService supplierConfigService;

    @Resource
    private OpenApiServiceProxy openApiServiceProxy;

    @Resource
    private OfcTaskService taskService;

    @Override
    public boolean cancelOrder(List<OfcSoHead> list) throws BusinessException {
        List<String> request = this.buildRequest(list);
        Long venderId = list.get(0).getVenderId();
        OfcSoHead so = list.get(0);

        Map<String, Object> config = supplierConfigService.findSupplierAndGetFulfillConfig(so.getRegionCode(), so.getSupplierDc(), so.getSupplierOrg(), so.getSupplierId());
        String wgPath = (String) config.get("wmsPath");
        String wareHouseCode = so.getWarehouseCode();;
//        if (DistributionWay.isPms(so.getDistributionWay()) && so.getOrderDistributionType().equals(DistributionType.ORDER_SO.getCode())) {
//            wareHouseCode = so.getPreWarehouseCode();
//        } else {
//            wareHouseCode = so.getWarehouseCode();
//        }
        cancelExternalCoordinationSoIfRequired(so);
        return this.wgServiceProxy.cancelOrder(request, wareHouseCode, wgPath, venderId);
    }

    private void cancelExternalCoordinationSoIfRequired(OfcSoHead so) {
        OfcSupplier fulfillConfig = supplierConfigService.findSupplier(so.getSupplierId(), so.getSupplierCode(), so.getSupplierGroup(), so.getSupplierOrg(), so.getRegionCode());
        if (fulfillConfig != null && fulfillConfig.externalCoordination()) {
            boolean interceptInTime = disableCreateExternalCoordinationSoTask(so);
            if (!interceptInTime) {
                withdrawSalesOrder(so, fulfillConfig);
            }
        }
    }

    private void withdrawSalesOrder(OfcSoHead so, OfcSupplier fulfillConfig) {
        boolean success = openApiServiceProxy.withdrawSalesOrder(requestOfCancelExternalCoordinationSo(so, fulfillConfig), headersOfCancelExternalCoordinationSo(so));
        if (!success) {
            throw new BusinessException(CommonResult.ERROR, "failed on withdraw sales order");
        }
    }

    private boolean disableCreateExternalCoordinationSoTask(OfcSoHead so) {
        int affected = taskService.disablePendingTask(Long.valueOf(so.getSoBillCode()), OfcTaskType.SO_PUSH_ATP_API);
        log.info(so.getSoBillCode() + " found pending task: {}", affected);
        return affected > 0;
    }

    private Map<String, Object> requestOfCancelExternalCoordinationSo(OfcSoHead so, OfcSupplier fulfillConfig) {
        Map<String, Object> request = new HashMap<>();
        request.put("order_id", so.getSoBillCode());
        request.put("warehouse_code", fulfillConfig.externalCooperateWarehouse());
        request.put("vender_id", so.getVenderId());
        request.put("to_vender_id", fulfillConfig.externalCooperateWith());
        return request;
    }

    private Map<String, Object> headersOfCancelExternalCoordinationSo(OfcSoHead so) {
        Map<String, Object> headers = new HashMap<>();
        headers.put("venderId", so.getVenderId());
        return headers;
    }

    @Override
    protected List<String> buildRequest(List<OfcSoHead> list) {
        List<String> requestList = new ArrayList<>();
        for (OfcSoHead ofcSoHead : list) {

            log.info("【取消订单】【请求文固】【so单 code】{}", ofcSoHead.getSoCode());

            requestList.add(ofcSoHead.getSoCode());

        }
        return requestList;
    }
}
